#!/usr/bin/env python3
"""
音频格式转换工具
使用ffmpeg将wav文件转换为其他格式进行测试
"""
import subprocess
import os
import sys

def convert_audio(input_file, output_format):
    """转换音频格式"""
    if not os.path.exists(input_file):
        print(f"❌ 输入文件不存在: {input_file}")
        return False
    
    # 构建输出文件名
    base_name = os.path.splitext(input_file)[0]
    output_file = f"{base_name}.{output_format}"
    
    try:
        # 根据格式选择ffmpeg参数
        if output_format == "mp3":
            cmd = ["ffmpeg", "-i", input_file, "-acodec", "mp3", "-ab", "128k", "-y", output_file]
        elif output_format == "flac":
            cmd = ["ffmpeg", "-i", input_file, "-acodec", "flac", "-y", output_file]
        elif output_format == "m4a":
            cmd = ["ffmpeg", "-i", input_file, "-acodec", "aac", "-ab", "128k", "-y", output_file]
        elif output_format == "ogg":
            cmd = ["ffmpeg", "-i", input_file, "-acodec", "libvorbis", "-ab", "128k", "-y", output_file]
        else:
            print(f"❌ 不支持的输出格式: {output_format}")
            return False
        
        # 执行转换
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode == 0:
            print(f"✅ {input_file} -> {output_file}")
            return True
        else:
            print(f"❌ 转换失败: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"❌ 转换异常: {e}")
        return False

def main():
    if len(sys.argv) < 2:
        print("用法: python convert_audio.py <input_wav_file>")
        print("示例: python convert_audio.py test.wav")
        sys.exit(1)
    
    input_file = sys.argv[1]
    
    if not input_file.lower().endswith('.wav'):
        print("警告: 建议使用wav文件作为输入以获得最佳质量")
    
    # 支持的输出格式
    formats = ["mp3", "flac", "m4a", "ogg"]
    
    print(f"正在转换 {input_file} 为多种格式...")
    
    success_count = 0
    for fmt in formats:
        if convert_audio(input_file, fmt):
            success_count += 1
    
    print(f"\n转换完成: {success_count}/{len(formats)} 格式成功")

if __name__ == "__main__":
    main() 